<template>
  <el-card>
    <div slot="header">
      <h3>区域商品起售量</h3>
    </div>
    <div>
      <LabelSelect
        label="操作类型"
        :value.sync="optionTypes.current"
        :options="optionTypes.options"
        @change="handleChangeOptionTypes"
      />
      <el-divider class="filter-tips" content-position="left">注意：如果变更过滤省，会清空表格已填写数据</el-divider>
      <el-row>
        <skus-table
          ref="skusTable"
          :defaultMinWidth="100"
          :tableHeight="480"
          :dataSource="TableInfo.list"
          :columns="TableInfo.columns"
          :loading="TableInfo.loading"
          @handleCancelSelect="handleDelete"
        >
          <div slot="content_context" class="table-header">
            <LabelSelect
              multiple
              clearable
              filterable
              label="过滤省"
              labelWidth="70px"
              slot="conditionSlot"
              class="senior-select-wrap"
              :value.sync="filterCodes"
              :options="provinceOptions"
              @change="handleFilterListByProvince"
            />
            <!-- 按钮操作栏 -->
            <BtnRender :render="renderBtnsBar" />
          </div>
        </skus-table>
      </el-row>
      <!-- 关联商品 -->
      <AssociateGoodsDialog
        ref="associateRef"
        :visible.sync="dialogVisible"
        @getResults="updateTableListByAssociateGoods"
      />
      <!-- 高级关联 -->
      <senior-linked-dialog
        :visible.sync="seniorLinked.visible"
        :columns="seniorLinked.columns"
        :dataSource="seniorLinked.dataSource"
        @seniorSearchResult="updateTableListBySeniorLinked"
      >
        <LabelSelect
          bold
          clearable
          filterable
          label="销售省"
          slot="conditionSlot"
          class="senior-select-wrap"
          :value.sync="seniorLinked.provinceCode"
          :options="provinceOptions"
        />
      </senior-linked-dialog>
    </div>
  </el-card>
</template>
<script>
import { mapGetters } from 'vuex';
import BtnRender from '@/components/JSXRender/BtnRender';
import SkusTable from '@/components/skusTable';
import LabelSelect from '@/pages/commodity/components/LabelSelect';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import AssociateGoodsDialog from './components/AssociateGoodsDialog';
import { TableInfo } from '@/utils/getUtils';
import { getListPageBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { setAuthBtnId, createExcelByExport, generateUuid, isResponseSuccess } from '@/utils/bizUtils';
import {
  OPTION_TYPES,
  OPTION_TYPES_OPTIONS,
  EDIT_TABLE_COLUMNS,
  NOT_EDIT_TABLE_COLUMNS,
  MAX_EDIT_LIMITS,
  ERROR_MSG_COL
} from './constants';
import {
  getAreaSaleMinListService,
  submitService,
  exportService,
  importUrl,
  getProvinceByLoginUserService
} from '@/api/commodity/commodityInfoEdit/areaStartingSalesQuantity';
export default {
  components: {
    BtnRender,
    SkusTable,
    LabelSelect,
    SeniorLinkedDialog,
    AssociateGoodsDialog
  },
  data () {
    return {
      TableInfo: new TableInfo({ columns: EDIT_TABLE_COLUMNS }),
      dialogVisible: false, // 关联商品弹框开关
      seniorLinked: {
        visible: false,
        columns: [{ label: 'SKU编码', prop: 'skuNo', type: 'textarea' }],
        dataSource: [{ skuNo: '' }],
        provinceCode: '',
      },
      optionTypes: {
        current: OPTION_TYPES.Edit,
        options: OPTION_TYPES_OPTIONS
      },
      btnLoading: {
        export: false,
        submit: false
      },
      skuNos: [], // 已关联商品编码集合
      provinceOptions: [],
      filterCodes: [], // 过滤省条件code集合
      dataSource: [], // 关联商品|高级关联 关联后的数据源
    }
  },
  created () {
    this.setProvinceOptions()
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    // 没有异常数据
    hasNoErrMsgs () {
      const hasNoErr = this.TableInfo.list.every(item => !item[ERROR_MSG_COL.key])
      return hasNoErr
    }
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnBars = [
        {
          label: '一键清除异常数据',
          method: this.handleClearAbnormalData,
          disabled: this.hasNoErrMsgs
        },
        {
          label: '高级关联',
          method: this.handleSeniorAssociate,
          hasAuth: true
        },
        {
          label: '关联商品',
          method: this.handleAssociateGoods,
          hasAuth: true
        },
        {
          label: '模板导出',
          method: this.handleTempExport,
          loading: this.btnLoading.export,
        },
        {
          label: '数据导入',
          action: importUrl,
          methods: { handleUploadSuccess: this.handleUploadSuccess },
          isImport: true,
          loadingFn: this.TableInfo.setLoading,
        },
        {
          label: '提交',
          method: this.handleSubmit,
          loading: this.btnLoading.submit,
          disabled: this.TableInfo.isNullList(),
          hasAuth: true
        }
      ]
      return getListPageBtnsBar(h, btnBars, this.showBtn)
    },
    // 删除
    handleDelete ({ index }) {
      this.TableInfo.removeList(index)
    },
    // 切换操作类型
    handleChangeOptionTypes () {
      this.updateTableColumns()
      this.TableInfo.setList(this.TableInfo.list.map(item => ({ ...item, [ERROR_MSG_COL.key]: '' })))
    },
    // 清空异常数据
    handleClearAbnormalData () {
      const updateList = this.TableInfo.list.filter(item => !item[ERROR_MSG_COL.key])
      this.TableInfo.setList(updateList)
    },
    // 高级关联
    handleSeniorAssociate () {
      setAuthBtnId('高级关联')
      this.seniorLinked.visible = true
    },
    // 关联商品
    handleAssociateGoods () {
      setAuthBtnId('关联商品')
      this.dialogVisible = true
    },
    // 模板导出
    async handleTempExport () {
      const data = {
        isTemplateFlag: this.TableInfo.isNullList() ? '1' : '2',
        skuNos: _.uniq(this.TableInfo.getListAttrs('skuNo')),
        provinceNo: _.uniq(this.TableInfo.getListAttrs('provinceNo'))
      }
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await exportService(data, loadingFn)
      createExcelByExport({ excelTitle: `区域商品起售量_${generateUuid()}`, res })
    },
    // 模板导入成功
    handleUploadSuccess (res) {
      if (!isResponseSuccess(res)) return
      this.filterCodes = [] // 导入时清空筛选省条件
      this.TableInfo.setList(res?.retData ?? [])
      this.dataSource = _.cloneDeep(this.TableInfo.list)
    },
    // 提交
    async handleSubmit () {
      const data = {
        dealType: this.optionTypes.current,
        dtos: this.TableInfo.list
      }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await submitService(data, loadingFn)
      if (res?.retStatus != '1') return
      if (res?.retData.length == 0) {
        this.$message.success('提交成功')
        return this.$router.push({ name: 'chageFromManageList' })
      }
      this.$message.warning('有异常原因，无法提交')
      this.TableInfo.setColumns([
        ERROR_MSG_COL,
        ...this.TableInfo.columns.filter(item => item.key != ERROR_MSG_COL.key)
      ])
      this.TableInfo.setList(res.retData)
    },
    // 过滤省
    handleFilterListByProvince () {
      this.setFilterListByProvince()
    },
    // 设置过滤省表格集合
    setFilterListByProvince () {
      if (this.filterCodes.length == 0) return this.TableInfo.setList(this.dataSource)
      const filterList = this.dataSource.filter(item => this.filterCodes.includes(item.provinceNo))
      this.TableInfo.setList(filterList)
      this.updateTableColumns()
    },
    // 获取表格是否可编辑状态
    getTableCanEditState () {
      const hasExceedLimits = this.TableInfo.list.length > MAX_EDIT_LIMITS // 当前表格数量超过最大可编辑限制值
      const isDeleteType = this.optionTypes.current == OPTION_TYPES.Delete // 当前是删除类型
      const cannotEdit = hasExceedLimits || isDeleteType // 当前表格是否可编辑
      return { hasExceedLimits, isDeleteType, cannotEdit }
    },
    // 更新表列
    updateTableColumns () {
      const { hasExceedLimits, isDeleteType, cannotEdit } = this.getTableCanEditState()
      if (!isDeleteType && hasExceedLimits) this.$message.warning(`最大可编辑数量为${MAX_EDIT_LIMITS}，超出请导出excel进行编辑`)
      this.TableInfo.setColumns(cannotEdit ? NOT_EDIT_TABLE_COLUMNS : EDIT_TABLE_COLUMNS)
    },
    // 高级查询更新表格数据
    updateTableListBySeniorLinked (skuNos) {
      const data = {
        skuNos: [...new Set(skuNos)],
        provinceNo: this.seniorLinked.provinceCode ? [this.seniorLinked.provinceCode] : null
      }
      this.setTableList(data)
    },
    // 关联商品更新表格数据
    updateTableListByAssociateGoods (results) {
      const skuNos = results.map(row => row.skuNo)
      const data = { skuNos: [...new Set(skuNos)] }
      this.setTableList(data)
    },
    // 设置表格数据
    async setTableList (data) {
      if (data?.skuNos) this.skuNos = data.skuNos
      if (this.skuNos?.length == 0) return this.$message.warning('请勾选关联商品')
      const res = await getAreaSaleMinListService(data, this.TableInfo.setLoading)
      if (res?.retData) {
        // 过滤掉已经存在的SKU
        const remainingList = this.TableInfo.list.filter(item => !this.skuNos.includes(item.skuNo))
        // 加入新关联的商品
        this.TableInfo.setList([...remainingList, ...res.retData])
        this.dataSource = _.cloneDeep(this.TableInfo.list)
        this.handleFilterListByProvince()
        this.updateTableColumns()
      }
    },
    // 设置省下拉集合
    async setProvinceOptions () {
      const res = await getProvinceByLoginUserService()
      const areaInfos = res?.retData ?? []
      this.provinceOptions = _.uniqBy(
        areaInfos.map(item => ({ value: item.provinceCode, label: item.provinceName })),
        'value'
      )
    },
  }
}
</script>
<style lang="less" scoped>
.el-divider--horizontal {
  margin: 10px 0;
}
.senior-select-wrap {
  margin-bottom: 10px;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
}
.filter-tips {
  margin: 20px 0;
  .el-divider__text {
    font-size: 10px;
    left: 12px;
    color: #F56C6C;
  }
}
</style>
